import { DropdownMenu, DropdownMenuContent, DropdownMenuSeparator, DropdownMenuTrigger } from "../ui/dropdown-menu";
import { Button, ButtonProps } from "../ui/button";
import { PlusIcon, TimeIcon, TrashIcon, UserIcon } from "../Icons";
import { MouseEvent, ReactNode, useState } from "react";
import { AlertAnswer } from "../Customs";
import { useAppDispatch } from "@/hook/useRedux";
import { changeTaskDate, removeTaskItem } from "@/redux/tasks/tasksSlice";
import { DatePicker } from "../DatePicker/DatePicker";

export const TaskCardMenu = ({ taskData, setNewTask, children }: { taskData: Task, setNewTask: (bool: boolean) => void, children: ReactNode }) => {
  const [dropMenu, setDropMenu] = useState(false);
  const [removeTask, setRemoveTask] = useState(false);

  const dispatch = useAppDispatch()

  const removeTaskCard = () => {
    dispatch(removeTaskItem({ id: +taskData.id, columnId: taskData.column_id }));
    setRemoveTask(false);
  };

  const handleOpenDropMenu = (event: React.MouseEvent<HTMLButtonElement>) => {
    event.stopPropagation();
    setDropMenu(!dropMenu);
  };

  const changeEndDate = (date: any) => {
    dispatch(changeTaskDate({ columnId: taskData.column_id, taskId: taskData.id, date: date.end_date }))
  }

  type buttonProps = ButtonProps
  const btnMenuConfig: buttonProps = {
    className: 'flex w-full items-center justify-start gap-2 pl-2',
    variant: 'ghost',
  }

  type EventAction = () => void;
  const handleEvent = <T extends HTMLElement>(e: MouseEvent<T>, action: EventAction) => {
    e.stopPropagation();
    setDropMenu(false);
    action();
  }

  const createSubtaskBtn = (e: MouseEvent<HTMLButtonElement>) => handleEvent(e, () => setNewTask(true));
  const removeTaskBtn = (e: MouseEvent<HTMLButtonElement>) => handleEvent(e, () => setRemoveTask(true));

  return <>
    <DropdownMenu open={dropMenu} onOpenChange={setDropMenu}>
      <DropdownMenuTrigger
        onClick={handleOpenDropMenu}
        asChild
      >
        {children}
      </DropdownMenuTrigger>
      <DropdownMenuContent onClick={(e) => e.stopPropagation()} className='p-0'>
        <Button onClick={createSubtaskBtn} {...btnMenuConfig}>
          <PlusIcon size={16} /> Подзадача
        </Button>
        <Button {...btnMenuConfig}>
          <UserIcon size={16} /> Исполнитель
        </Button>
        <DatePicker setTaskDate={changeEndDate} end_date={taskData.end_date} clear={changeEndDate} side='right' >
          <Button {...btnMenuConfig}>
            <TimeIcon size={16} /> Дата
          </Button>
        </DatePicker>
        <DropdownMenuSeparator />
        <Button
          {...btnMenuConfig}
          onClick={removeTaskBtn}
        >
          <TrashIcon size={16} color="red" /> Удалить
        </Button>
      </DropdownMenuContent>
    </DropdownMenu>
    <AlertAnswer open={removeTask} cancel={() => setRemoveTask(false)} accept={removeTaskCard} text={`Вы действительно хотите удалить задачу ${taskData.name}?`} />
  </>
}